package com.gtmc.gclub.chat.service;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.gtmc.gclub.chat.bean.MyException;
import com.gtmc.gclub.chat.bean.Result;
import com.gtmc.gclub.chat.constants.ChatConstant;
import com.gtmc.gclub.chat.constants.CommonProperties;
import com.gtmc.gclub.chat.dao.TmDealerMapper;
import com.gtmc.gclub.chat.dao.TrUserEnterpriseMapper;
import com.gtmc.gclub.chat.dao.WxTokenMapper;
import com.gtmc.gclub.chat.dao.WxUserOwnerMapper;
import com.gtmc.gclub.chat.external.service.WeChatPushServiceInterface;
import com.gtmc.gclub.chat.jmessage.UserOperator;
import com.gtmc.gclub.chat.model.TmDealer;
import com.gtmc.gclub.chat.model.TrUserEnterprise;
import com.gtmc.gclub.chat.model.WxMaterialFile;
import com.gtmc.gclub.chat.model.WxToken;
import com.gtmc.gclub.chat.util.DateUtil;
import com.gtmc.gclub.chat.util.MD5Util;
import com.gtmc.gclub.chat.util.RandomNum;
import com.gtmc.gclub.chat.vo.WxMaterialBaseVo;
import com.gtmc.gclub.chat.vo.WxMaterialFileVo;
import com.gtmc.gclub.chat.vo.WxMaterialMedia;
import com.gtmc.gclub.chat.vo.WxMaterialNews;
import com.gtmc.gclub.common.WxMaterialTypeEnum;
import com.gtmc.gclub.common.WxMediaFileSourceType;
import com.gtmc.gclub.common.WxUtil;
import com.gtmc.gclub.wx.dto.AccessToken;
import com.gtmc.gclub.wx.dto.DepUser;
import com.gtmc.gclub.wx.dto.Department;
import com.gtmc.gclub.wx.dto.DepartmentList;
import com.gtmc.gclub.wx.dto.JsApiTicket;
import com.gtmc.gclub.wx.dto.TagList;
import com.gtmc.gclub.wx.dto.TagUser;
import com.gtmc.gclub.wx.dto.WxJsApiAuth;
import com.gtmc.gclub.wx.dto.WxUserInfo;
import com.infoservice.filestore.FileStore;
import com.infoservice.filestore.FileStoreException;

/**
 * @author kaihu
 *
 */
@Service
@Transactional
public class WxService {
	private static Logger logger = LoggerFactory.getLogger(WxService.class);
	@Autowired
	private WxTokenMapper wxTokenMapper;
	@Autowired
	private CommonProperties commonProperties;

	@Autowired
	private TmDealerMapper tmDealerMapper;

	@Autowired
	private TrUserEnterpriseMapper trUserEnterpriseMapper;
	
	@Autowired
	private UserOperator userOperator;
	
	@Autowired
	private WxMaterialFileService wxMaterialFileService;
	
	@Autowired
	private WeChatPushServiceInterface weChatPushServiceInterface;

	public WxToken getWxToken() {
		logger.info("获取微信ticket:getWxToken");
		WxToken token = wxTokenMapper.selectByPrimaryKey(commonProperties.getTokenId());
		if (token == null) {
			// 获取token,插入表中，并返回
//			AccessToken acc = WxUtil.getWxToken(commonProperties.corpid, commonProperties.corpsecret);
			String tokenJson = weChatPushServiceInterface.getWxPublishToken();
			AccessToken acc = JSON.parseObject(tokenJson, AccessToken.class);
			if(acc.getToken()!=null && acc.getAccess_token()==null) {
				acc.setAccess_token(acc.getToken());
			}
			logger.debug("token获取结果："+acc);
			// 修改获取token的方式，由其他微服务获取
			if (acc == null)
				return token;
			WxToken bean = new WxToken();
			bean.setId(commonProperties.getTokenId());
			bean.setAccessToken(acc.getAccess_token());
			bean.setExpiresIn(acc.getExpires_in());
			bean.setCreateDate(new Date());
			bean.setStartTime(System.currentTimeMillis());
			wxTokenMapper.insert(bean);
			return bean;
		} else {
			int expires = token.getExpiresIn() - 500;
			Long startTime = token.getStartTime();
			Long currentTime = System.currentTimeMillis();
			long time = (currentTime - startTime) / 1000;
			if (time <= expires)
				return token;
			// 已超时，重新获取，更新，返回
//			AccessToken acc = WxUtil.getWxToken(commonProperties.corpid, commonProperties.corpsecret);
			String tokenJson = weChatPushServiceInterface.getWxPublishToken();
			AccessToken acc = JSON.parseObject(tokenJson, AccessToken.class);
			if(acc.getToken()!=null && acc.getAccess_token()==null) {
				acc.setAccess_token(acc.getToken());
			}
			logger.debug("token获取结果："+acc);
			if (acc == null)
				return null;
			WxToken bean = new WxToken();
			bean.setId(commonProperties.getTokenId());
			bean.setAccessToken(acc.getAccess_token());
			bean.setExpiresIn(acc.getExpires_in());
			bean.setCreateDate(new Date());
			bean.setStartTime(System.currentTimeMillis());
			wxTokenMapper.updateByPrimaryKey(bean);
			return bean;
		}
	}

	/**
	 * 获取微信jsticket
	 * 
	 * @author qianjs163@163.com
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public WxJsApiAuth getWxJsApiAuth(String jsUrl) {
		logger.info("获取imessage的有效签名:getWxJsApiAuth");
		// String url = "";
		// try {
		// url = URLEncoder.encode(jsUrl, "utf-8");
		// } catch (UnsupportedEncodingException e) {
		// logger.error("urlencode报错");
		// }
		String token = getWxToken().getAccessToken();
		WxToken jsTicket = wxTokenMapper.selectByPrimaryKey(commonProperties.ticketId);
		if (jsTicket == null) {
			// 为空，获取信息并插入
			JsApiTicket ticket = WxUtil.getJsApiTicket(token);
			if (ticket == null)
				logger.error("获取WxJsTicket失败");
			jsTicket = new WxToken();
			jsTicket.setId(commonProperties.ticketId);
			jsTicket.setCreateDate(new Date());
			jsTicket.setStartTime(System.currentTimeMillis());
			jsTicket.setExpiresIn(ticket.getExpires_in());
			jsTicket.setAccessToken(ticket.getTicket());
			wxTokenMapper.insert(jsTicket);
		} else {
			// 已存在，先更新
			int expires = jsTicket.getExpiresIn() - 500;
			Long startTime = jsTicket.getStartTime();
			Long currentTime = System.currentTimeMillis();
			long time = (currentTime - startTime) / 1000;
			if (time >= expires) {
				JsApiTicket ticket = WxUtil.getJsApiTicket(token);
				if (ticket == null)
					logger.error("获取WxJsTicket失败");
				jsTicket.setId(commonProperties.ticketId);
				jsTicket.setCreateDate(new Date());
				jsTicket.setStartTime(System.currentTimeMillis());
				jsTicket.setExpiresIn(ticket.getExpires_in());
				jsTicket.setAccessToken(ticket.getTicket());
				wxTokenMapper.updateByPrimaryKey(jsTicket);
			}

		}
		String jsApi = jsTicket.getAccessToken();
		String radom = RandomNum.createRandomString(20);
		long timestamp = System.currentTimeMillis();
		String m = "jsapi_ticket=" + jsApi + "&noncestr=" + radom + "&timestamp=" + timestamp + "&url=" + jsUrl;
		String signature = MD5Util.getSha1(m);
		WxJsApiAuth auth = new WxJsApiAuth();
		auth.setAppId(commonProperties.corpid);
		auth.setNonceStr(radom);
		auth.setSignature(signature);
		auth.setTimestamp(timestamp);
		return auth;
	}

	/**
	 * 
	 * @author qianjs163@163.com
	 * @param serId
	 * @return
	 */
	public WxMaterialFileVo getFileUrl(String serId,WxMaterialTypeEnum type,WxMediaFileSourceType meterialType) throws Exception{
		WxToken token = getWxToken();
		WxMaterialFileVo fileEntity = new WxMaterialFileVo() ;
		switch (type) {
		case image:
			fileEntity = WxUtil.getImage(token.getAccessToken(), serId,meterialType);
			break;
		case video:
			fileEntity = WxUtil.getVideo(token.getAccessToken(), serId,meterialType);
			break;
		case voice:
			fileEntity = WxUtil.getVoice(token.getAccessToken(), serId,meterialType);
			break;

		default:
			break;
		}
		byte[] b = fileEntity.getData();
		logger.error("从微信获取媒体文件流：mediaId："+serId+";type："+type.name()+";sourceType："+meterialType.name());
		String fileUrl = "";
		if (b == null) {
			logger.error("从微信获取流失败：getFileUrl");
			throw new MyException("0", "网络异常");
		} else {
			logger.debug("从微信获取到的媒体文件："+b.length);
			try {
				String extName = "" ;
				switch (type) {
				case image:
					extName = ".jpg";
					break;
				case video:
					extName = ".mp4";
					break;
				case voice:
					extName = ".mp3";
					break;

				default:
					break;
				}
				String name = "WX_"+type.name()+"_"+meterialType.name()+"_"+DateUtil.format(new Date(), "HHmmssSSS") + RandomNum.createRandomString(6) + extName;
				fileUrl = FileStore.getInstance().write("nd02", "fs01", name, b);
				// fileUrl = FileStore.getInstance().getDomainURL(fileId);
			} catch (Exception e) {
				logger.error("保存FileStore失败：getFileUrl" + e.getMessage());
				throw new MyException("0", "网络异常");
			}

		}
		fileEntity.setLocalUrl(fileUrl);
		return fileEntity;
	}
	
	/**
	 * 获取微信接口信息
	 * 
	 * @author qianjs163@163.com
	 * @param id
	 * @return
	 */
	public Map<String, List<TrUserEnterprise>> getDepartmentList() {
		String token = getWxToken().getAccessToken();
		DepartmentList deList = WxUtil.getDepartmentList(token, commonProperties.getDepId());
		// 售前
		TagList qianList = WxUtil.getTagList(token, commonProperties.tagidBefore);
		// 售后
		TagList houList = WxUtil.getTagList(token, commonProperties.tagidAfter);
		// 部门成员信息
		DepUser du = WxUtil.getDepUser(token, commonProperties.getDepId(), "1", "1");
		//
		List<TrUserEnterprise> dbList = trUserEnterpriseMapper.selectAll();
		TrUserEnterprise user = null;
		List<TrUserEnterprise> yList = new ArrayList<TrUserEnterprise>();
		List<TrUserEnterprise> xList = new ArrayList<TrUserEnterprise>();
		List<WxUserInfo> singList = du.getUserList();
		List<Department> depList = deList.getDepartment();
		for (int i = 0; i < singList.size(); i++) {
			WxUserInfo userInfo = singList.get(i);
			user = new TrUserEnterprise();
			user.setWxUserId(userInfo.getUserid());
			boolean flag = true;
			for (int j = 0; j < dbList.size(); j++) {
				TrUserEnterprise dbUser = dbList.get(j);
				if (userInfo.getUserid().equals(dbUser.getWxUserId())) {
					flag = false;
					user.setId(dbUser.getId());
					if (getDealerType(userInfo.getUserid(), qianList.getUserlist())) {
						user.setDealerCdType(new BigDecimal(ChatConstant.SHOU_QIAN));
					} else if (getDealerType(userInfo.getUserid(), houList.getUserlist())) {
						user.setDealerCdType(new BigDecimal(ChatConstant.SHOU_HOU));
					} else {
						continue;
					}
					user.setWeixinName(userInfo.getName());
					if (!(userInfo.getAvatar() == null || "".equals(userInfo.getAvatar()))) {
						// user.setIconsPhoto(userInfo.getAvatar() +
						// ChatConstant.WX_SMALL_IMAGE);
						user.setIconsPhoto(userInfo.getAvatar());
					} else {
						user.setIconsPhoto("");
					}
					String deCode = getDealerCode(userInfo.getDepartment(), depList);
					// String deCode =
					// getDealerCode(userInfo.getDepartment().get(0), depList);
					user.setDealerCode(deCode);
					TmDealer dealer = new TmDealer();
					dealer.setDealerCode(deCode);
					dealer = tmDealerMapper.selectOne(dealer);
					if (dealer != null) {
						user.setDealerName(dealer.getDealerName());
					}

					if (dbUser.getJmessageCode() == null || "".equals(dbUser.getJmessageCode())) {
						Result<Map> result = userOperator.registerAdmins(
								ChatConstant.IMESSAGE_PREFIX + userInfo.getUserid(), commonProperties.pwd);
						if (!"1".equals(String.valueOf(result.getReturnFlag()))) {
							logger.error(ChatConstant.IMESSAGE_PREFIX + userInfo.getUserid() + result.getErrorMsg());
							user.setJmessageCode("");
						} else {
							user.setJmessageCode(ChatConstant.IMESSAGE_PREFIX + userInfo.getUserid());
						}
					} else {
						user.setJmessageCode(dbUser.getJmessageCode());
					}
					yList.add(user);
				}
			}
			if (flag) {
				user.setWeixinName(userInfo.getName());
				if (getDealerType(userInfo.getUserid(), qianList.getUserlist())) {
					user.setDealerCdType(new BigDecimal(ChatConstant.SHOU_QIAN));
				} else if (getDealerType(userInfo.getUserid(), houList.getUserlist())) {
					user.setDealerCdType(new BigDecimal(ChatConstant.SHOU_HOU));
				} else {
					continue;
				}
				if (!(userInfo.getAvatar() == null || "".equals(userInfo.getAvatar()))) {
					// user.setIconsPhoto(userInfo.getAvatar() +
					// ChatConstant.WX_SMALL_IMAGE);
					user.setIconsPhoto(userInfo.getAvatar());
				} else {
					user.setIconsPhoto("");
				}
				user.setDealerCode(getDealerCode(userInfo.getDepartment(), depList));
				// user.setDealerCode(getDealerCode(userInfo.getDepartment().get(0),
				// depList));
				Result<Map> result = userOperator.registerAdmins(ChatConstant.IMESSAGE_PREFIX + userInfo.getUserid(),
						commonProperties.pwd);
				if (!"1".equals(String.valueOf(result.getReturnFlag()))) {
					logger.error(ChatConstant.IMESSAGE_PREFIX + userInfo.getUserid() + result.getErrorMsg());
					user.setJmessageCode("");
				} else {
					user.setJmessageCode(ChatConstant.IMESSAGE_PREFIX + userInfo.getUserid());
				}
				TmDealer dealer = new TmDealer();
				dealer.setDealerCode(user.getDealerCode());
				dealer = tmDealerMapper.selectOne(dealer);
				if (dealer != null) {
					user.setDealerName(dealer.getDealerName());
				}
				xList.add(user);
			}
		}
		Map<String, List<TrUserEnterprise>> map = new HashMap<String, List<TrUserEnterprise>>();
		map.put("yList", yList);
		map.put("xList", xList);
		return map;
	}

	/**
	 * 批量更新数据
	 * 
	 * @author qianjs163@163.com
	 * @return
	 */
	public void updateChatUser(Map<String, List<TrUserEnterprise>> map) {
		List<TrUserEnterprise> yList = map.get("yList");
		List<TrUserEnterprise> xList = map.get("xList");
		trUserEnterpriseMapper.deleteAll();
		if (yList.size() > 0) {
			trUserEnterpriseMapper.insertByBatchId(yList);
		}
		if (xList.size() > 0) {
			trUserEnterpriseMapper.insertByBatch(xList);
		}
	}

	// public String getDealerCode(int id, List<Department> list) {
	// for (int i = 0; i < list.size(); i++) {
	// Department dep = list.get(i);
	// int pid = dep.getId();
	// if (pid == id) {
	// return dep.getName();
	// }
	// }
	// return null;
	// }

	public String getDealerCode(List<Integer> deps, List<Department> list) {
		for (int i = 0; i < list.size(); i++) {
			Department dep = list.get(i);
			int pid = dep.getId();
			for (int j : deps) {
				if (pid == j) {
					return dep.getName();
				}
			}
		}
		return null;
	}

	public boolean getDealerType(String userId, List<TagUser> list) {
		for (int i = 0; i < list.size(); i++) {
			TagUser tag = list.get(i);
			if (userId.equals(tag.getUserid())) {
				return true;
			}
		}
		return false;
	}
	/**
	 * 获取图片、语音、视频素材参数实体
	 * @return
	 */
	public List<WxMaterialBaseVo> getAllMaterial(WxMaterialTypeEnum type)throws Exception{
		logger.debug("首先获取token");
		String token = getWxToken().getAccessToken();
//		logger.debug("获取token:"+token);
		logger.debug("开始拉取永久素材："+token);
		List<String> resJson = WxUtil.getAllMaterial(token,type);
		logger.debug("获取"+type.name()+"素材请求："+resJson.size());
		logger.debug("开始打印素材信息：");
		for(int i=0;i<resJson.size();i++) {
//			logger.debug("第"+i+"页素材："+resJson.get(i)+"\n");
		}
		logger.debug("打印素材信息结束");
		List<WxMaterialBaseVo> result = new ArrayList<WxMaterialBaseVo>();
		for(String mediaTempJsonStr : resJson) {
			WxMaterialBaseVo tempMediaEntity = JSON.toJavaObject(JSON.parseObject(mediaTempJsonStr), WxMaterialBaseVo.class);
			result.add(tempMediaEntity);
		}
		logger.debug(type.name()+"素材实体整合结果："+result.size());
		return result;
	}
	/**
	 * 上传媒体文件到微信
	 * @param file 文件对象
	 * @param type 文件类型
	 * @return 返回微信的mediaId
	 * @throws IOException 
	 */
	public String uploadFileToWeixin(File file,WxMaterialTypeEnum type) throws IOException {
		String tokenJson = weChatPushServiceInterface.getWxPublishToken();
//		String token = "5_XRGTx47cKTQ-pkWAHviqS2ltEXpMFfVnUQ3xZexmwxwE5ucT8xDtdvsTV0zNHW_-orlY7nmRPFaeDO8yip6oqqaW0BB2SSCKPxK9HMzrAC3_nr7EWDofeh8fv_C1MpHVcqAmQ4x5nUhhYMdANVHbAIAHPB";
		JSONObject tokenJsonObj = JSON.parseObject(tokenJson);
		String token = tokenJsonObj.getString("token") ;
		logger.debug("上传媒体文件"+type.name()+"到微信临时素材:token="+token+";type:"+type.name()+";file="+file.getPath()+";"+file.getAbsolutePath());
		String resJson = WxUtil.uploadTempSourceFile(token, type, file);
		JSONObject jsonObj = JSON.parseObject(resJson);
        if(jsonObj==null) {
        	logger.debug("文件上传到微信失败");
        	return null;
        }else {
        	logger.debug("文件上传到微信成功"+resJson);
        	file.delete();
        	return jsonObj.getString("media_id");
        }
	}
	
	/**
	 * 同步微信永久素材到本地DB、FileStore，仅供同步线程使用
	 */
	public void syncWxMaterialFileToDbThreadMethod(WxMaterialTypeEnum needType) {
		try {
		String logStart = "syncWxMaterialFileToDbThreadMethod" ;
		logger.debug(logStart+"首先读取数据库中已经存在的永久素材列表");
		List<String> dbMedias = new ArrayList<String>();
		List<String> wxMedias = new ArrayList<String>();
		Map<String,WxMaterialFile> wxMediasDbDetail = new HashMap<String,WxMaterialFile>();
		Map<String,WxMaterialMedia> wxMediasDetail = new HashMap<String,WxMaterialMedia>();
		// 如果这有必要，则加入状态限制
		WxMaterialFile record = new WxMaterialFile();
		record.setAppid(WxMaterialFile.APPID_GZ);
		record.setStatus(WxMaterialFile.STATUS_USEFUL);
		List<WxMaterialFile> allmeterialDb = wxMaterialFileService.getAll(record);
		logger.debug(logStart+"数据库中已经记录的素材："+allmeterialDb);
		for(WxMaterialFile tempFileDb :allmeterialDb) {
			dbMedias.add(tempFileDb.getMediaId());
			wxMediasDbDetail.put(tempFileDb.getMediaId(), tempFileDb);
		}
		for(WxMaterialTypeEnum type : WxMaterialTypeEnum.values()) {
			if(needType!=null && type != needType) {
				continue;
			}
			// 图文先不调。有时间了在调，而且图文是可以更新的，这个比较麻烦
			if(type==WxMaterialTypeEnum.text || type==WxMaterialTypeEnum.news || type==WxMaterialTypeEnum.mpnews) {
				continue;
			}
			logger.debug(logStart+"从微信永久素材中获取"+type.name()+"类型的素材");
			List<WxMaterialBaseVo> allMaterial = null;
			try {
				allMaterial = getAllMaterial(type);
			} catch (Exception e) {
				logger.error(logStart+"从微信获取资源列表出现异常："+e.getMessage());
				e.printStackTrace();
			}
			System.out.println(logStart+"直接从微信端获取的"+type+"素材列表："+allMaterial.size());
			for(WxMaterialBaseVo tempRoot : allMaterial) {
				List<Object> tempMedias = tempRoot.getItem();
				for(Object tempObj : tempMedias) {
					// 图文在这里暂不存储
					if(!StringUtils.equals(type.name(), WxMaterialTypeEnum.mpnews.name()) && !StringUtils.equals(type.name(), WxMaterialTypeEnum.news.name())) {
						WxMaterialMedia tempMedia = JSON.toJavaObject(JSON.parseObject(JSON.toJSONString(tempObj)), WxMaterialMedia.class);
						logger.debug(logStart+"媒体实体内容-json："+JSON.toJSONString(tempObj));
						tempMedia.setType(type);
						wxMediasDetail.put(tempMedia.getMedia_id(),tempMedia);
						wxMedias.add(tempMedia.getMedia_id());
						logger.debug(logStart+"参数转换之后，媒体实体内容,在这里只有图片和图文才有实际url，其他素材需要根据mediaId进行进一步操作："+tempMedia);
//						res.add(WxMaterialMedia.getH5JsonMap(tempMedia,WxMaterialTypeEnum.valueOf(type)));
//					}else if (StringUtils.equals(type.name(), WxMaterialTypeEnum.news.name())) {
//						WxMaterialNews tempMedia = JSON.toJavaObject(JSON.parseObject(JSON.toJSONString(tempObj)), WxMaterialNews.class);
//						res.add(WxMaterialNews.getH5JsonMap(tempMedia));
					}
				}
			}
		}
		// 拿到数据库中的medias和微信的medias之后，开始对比
		// 首先先操作增加的素材
		List<String> newMedias = (List<String>) CollectionUtils.subtract(wxMedias, dbMedias);
		logger.debug(logStart+"微信新增的素材有："+newMedias);
		logger.debug(logStart+"微信新增的素材一共有"+newMedias.size()+"个");
		for(String newMediaId : newMedias) {
			WxMaterialMedia newMedia = wxMediasDetail.get(newMediaId);
			logger.debug(logStart+"操作的媒体对象："+newMedia);
			WxMaterialFileVo urlEntity = null ;
			logger.debug("首先判断媒体类型："+newMedia.getType());
			if(StringUtils.equals(newMedia.getType().name(), WxMaterialTypeEnum.image.name())
					|| StringUtils.equals(newMedia.getType().name(), WxMaterialTypeEnum.video.name())
					|| StringUtils.equals(newMedia.getType().name(), WxMaterialTypeEnum.voice.name())) {
				logger.debug(logStart+"本次操作素材类型为"+newMedia.getType().name()+"，开始上传素材到本地服务器");
				try {
					urlEntity = getFileUrl(newMediaId, newMedia.getType(), WxMediaFileSourceType.permanent);
					urlEntity.setTitle(newMedia.getName());
					logger.debug("urlEntity:"+urlEntity);
				} catch (Exception e) {
					logger.debug(logStart+"上传媒体文件到本地失败："+e.getMessage());
					e.printStackTrace();
				}
				logger.debug(logStart+"上传"+newMedia.getType().name()+"完毕，素材访问地址："+urlEntity);
			}
			WxMaterialFile dbNewMedia = new WxMaterialFile();
			dbNewMedia.setAppid(WxMaterialFile.APPID_GZ);
			dbNewMedia.setCreateDate(new Date());
			// voice和image的title和description都不在通过mediaId获取素材的接口中，都在素材列表中（如果有的话）
			dbNewMedia.setDescription(
					(!StringUtils.equals(newMedia.getType().name(), WxMaterialTypeEnum.video.name())) 
					? newMedia.getDescription() : urlEntity.getDescription());
			dbNewMedia.setLocalUrl(urlEntity.getLocalUrl());
			dbNewMedia.setMediaId(newMediaId);
			dbNewMedia.setStatus(WxMaterialFile.STATUS_USEFUL);
			dbNewMedia.setTitle(newMedia.getName());// 这里不适合图文
			logger.debug("这里为"+newMedia.getType().name()+"设置title:newMedia.getTitle()="+newMedia.getTitle()+";urlEntity.getTitle()="+urlEntity.getTitle()+";最终设置的title:"+dbNewMedia.getTitle());
			logger.debug("再看一下使用newMedia.getName()="+newMedia.getName());
			dbNewMedia.setType(newMedia.getType());
			dbNewMedia.setUpdateDate(new Date());
			logger.debug("查看一下url的情况type:"+newMedia.getType().name()+"：素材列表中的url："+newMedia.getUrl()+" ; urlEntity中的url:[local:"+urlEntity.getLocalUrl()+",wxUrl:"+urlEntity.getDownloadUrl());
			if(!StringUtils.equals(newMedia.getType().name(), WxMaterialTypeEnum.news.name())
					&& !StringUtils.equals(newMedia.getType().name(), WxMaterialTypeEnum.mpnews.name())) {
				logger.debug("非新闻类型，使用可下载的URL:"+urlEntity.getDownloadUrl());
				dbNewMedia.setWxUrl(urlEntity.getDownloadUrl());
			}else {
				logger.debug("新闻类型，使用文章URL:"+newMedia.getUrl());
				dbNewMedia.setWxUrl(newMedia.getUrl());
			}
			logger.debug(logStart+"插入新的微信素材到本地："+dbNewMedia);
			wxMaterialFileService.insert(dbNewMedia);
		}
		logger.debug("同步结束");
		logger.debug(logStart+"微信新增的素材有："+newMedias);
		logger.debug(logStart+"微信新增的素材一共有"+newMedias.size()+"个");
		}catch(Exception e) {
			logger.error("同步微信永久素材出错："+e);
			e.printStackTrace();
		}
		// 其次操作微信删除的素材。删除的话，，还有问题，，作为后续做吧，时间太紧张了。
//		List<String> delMedias = (List<String>) CollectionUtils.subtract(wxMedias, dbMedias);
//		logger.debug(logStart+"微信删除的素材："+delMedias);
//		logger.debug(logStart+"微信删除的素材共有"+delMedias.size()+"个");
//		for(String delMedia : delMedias) {
//			WxMaterialFile wxMaterialFile = wxMediasDbDetail.get(delMedia);
//			try {
//				logger.debug(logStart+"删除素材开始");
//				wxMaterialFileService.deleteMaterial(wxMaterialFile);
//				logger.debug(logStart+"删除素材结束");
//			} catch (FileStoreException e) {
//				logger.error(logStart+"删除微信永久素材本地文件失败："+wxMaterialFile.getLocalUrl());
//				e.printStackTrace();
//			}
//		}
		// 最后操作更新的素材（修改素材仅永久图文素材才可以做修改操作，这里目前没有把永久图文素材存储到本地）
	}
}
